<template>
  <div class="knowledge-graph">
    <!-- 页面头部 -->
    <div class="graph-header">
      <div class="container">
        <div class="header-content">
          <div class="header-info">
            <h1 class="page-title">
              <el-icon class="title-icon"><DataBoard /></el-icon>
              医疗知识图谱
            </h1>
            <p class="page-subtitle">探索医疗知识的关联与结构，助力精准诊疗</p>
          </div>
          <div class="graph-stats">
            <div class="stat-item">
              <span class="stat-number">{{ totalNodes }}</span>
              <span class="stat-label">知识节点</span>
            </div>
            <div class="stat-item">
              <span class="stat-number">{{ totalRelations }}</span>
              <span class="stat-label">关联关系</span>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 控制面板 -->
    <div class="control-panel">
      <div class="container">
        <div class="panel-content">
          <div class="search-section">
            <el-input
              v-model="searchQuery"
              placeholder="搜索疾病、症状、药物..."
              class="search-input"
              size="large"
              clearable
              @input="handleSearch"
            >
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
          </div>
          
          <div class="filter-section">
            <el-button-group>
              <el-button 
                :type="activeFilter === 'all' ? 'primary' : 'default'"
                @click="setFilter('all')"
              >
                全部
              </el-button>
              <el-button 
                :type="activeFilter === 'disease' ? 'primary' : 'default'"
                @click="setFilter('disease')"
              >
                疾病
              </el-button>
              <el-button 
                :type="activeFilter === 'symptom' ? 'primary' : 'default'"
                @click="setFilter('symptom')"
              >
                症状
              </el-button>
              <el-button 
                :type="activeFilter === 'drug' ? 'primary' : 'default'"
                @click="setFilter('drug')"
              >
                药物
              </el-button>
              <el-button 
                :type="activeFilter === 'department' ? 'primary' : 'default'"
                @click="setFilter('department')"
              >
                科室
              </el-button>
            </el-button-group>
          </div>
        </div>
      </div>
    </div>

    <!-- 知识图谱可视化区域 -->
    <div class="graph-container">
      <div class="container">
        <div class="graph-wrapper">
          <div class="graph-canvas" ref="graphCanvas" v-loading="loading">
            <!-- 这里将渲染知识图谱 -->
          </div>
          
          <!-- 侧边详情面板 -->
          <div class="detail-panel" v-if="selectedNode">
            <div class="panel-header">
              <h3 class="node-title">{{ selectedNode.name }}</h3>
              <el-tag :type="getNodeTypeColor(selectedNode.type)">
                {{ getNodeTypeName(selectedNode.type) }}
              </el-tag>
            </div>
            
            <div class="panel-content">
              <div class="node-description">
                <h4>详细描述</h4>
                <p>{{ selectedNode.description }}</p>
              </div>
              
              <div class="node-relations" v-if="selectedNode.relations && selectedNode.relations.length > 0">
                <h4>相关关联</h4>
                <ul class="relation-list">
                  <li 
                    v-for="relation in selectedNode.relations" 
                    :key="relation.id"
                    class="relation-item"
                    @click="focusNode(relation.target)"
                  >
                    <span class="relation-type">{{ relation.type }}</span>
                    <span class="relation-target">{{ relation.targetName }}</span>
                  </li>
                </ul>
              </div>
              
              <div class="node-properties" v-if="selectedNode.properties">
                <h4>属性信息</h4>
                <div class="property-grid">
                  <div 
                    v-for="(value, key) in selectedNode.properties" 
                    :key="key"
                    class="property-item"
                  >
                    <span class="property-key">{{ key }}</span>
                    <span class="property-value">{{ value }}</span>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 知识分类导航 -->
    <div class="knowledge-categories">
      <div class="container">
        <h2 class="section-title">知识分类</h2>
        <div class="categories-grid">
          <div 
            v-for="category in knowledgeCategories" 
            :key="category.id"
            class="category-card"
            @click="exploreCategory(category)"
          >
            <div class="category-icon" :style="{ backgroundColor: category.color }">
              <el-icon><component :is="category.icon" /></el-icon>
            </div>
            <div class="category-info">
              <h3 class="category-name">{{ category.name }}</h3>
              <p class="category-description">{{ category.description }}</p>
              <div class="category-stats">
                <span class="stat">{{ category.nodeCount }} 个节点</span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import { 
  DataBoard, 
  Search,
  FirstAidKit,
  User,
  Box,
  OfficeBuilding
} from '@element-plus/icons-vue'

// 响应式数据
const searchQuery = ref('')
const activeFilter = ref('all')
const loading = ref(true)
const selectedNode = ref(null)
const graphCanvas = ref(null)
const totalNodes = ref(0)
const totalRelations = ref(0)

// 知识分类数据
const knowledgeCategories = [
  {
    id: 1,
    name: '常见疾病',
    description: '心血管、呼吸系统等常见疾病知识',
    icon: 'FirstAidKit',
    color: '#ff6b6b',
    nodeCount: 156
  },
  {
    id: 2,
    name: '症状体征',
    description: '各种症状与疾病的关联关系',
    icon: 'User',
    color: '#4ecdc4',
    nodeCount: 234
  },
  {
    id: 3,
    name: '药物治疗',
    description: '药物作用机制与适应症',
    icon: 'Box',
    color: '#45b7d1',
    nodeCount: 198
  },
  {
    id: 4,
    name: '医疗科室',
    description: '各科室诊疗范围与专长',
    icon: 'OfficeBuilding',
    color: '#96ceb4',
    nodeCount: 32
  }
]

// 模拟知识图谱数据
const mockGraphData = {
  nodes: [
    // 疾病节点
    { id: 'disease_1', name: '高血压', type: 'disease', description: '血压持续升高的慢性疾病，是心血管疾病的主要危险因素', properties: { '发病率': '25.2%', '主要人群': '中老年人', '严重程度': '中等' } },
    { id: 'disease_2', name: '糖尿病', type: 'disease', description: '以高血糖为特征的代谢性疾病群', properties: { '发病率': '11.2%', '主要人群': '成年人', '严重程度': '中等' } },
    { id: 'disease_3', name: '冠心病', type: 'disease', description: '冠状动脉粥样硬化性心脏病', properties: { '发病率': '4.2%', '主要人群': '中老年人', '严重程度': '严重' } },
    
    // 症状节点
    { id: 'symptom_1', name: '头痛', type: 'symptom', description: '头部疼痛的症状，可能由多种原因引起', properties: { '常见程度': '很常见', '持续时间': '数小时-数天' } },
    { id: 'symptom_2', name: '胸痛', type: 'symptom', description: '胸部疼痛，可能提示心血管或肺部疾病', properties: { '常见程度': '常见', '紧急程度': '高' } },
    { id: 'symptom_3', name: '多尿', type: 'symptom', description: '尿量增多，常见于糖尿病患者', properties: { '常见程度': '常见', '提示疾病': '糖尿病' } },
    
    // 药物节点
    { id: 'drug_1', name: '阿司匹林', type: 'drug', description: '解热镇痛抗炎药，具有抗血小板聚集作用', properties: { '类型': '解热镇痛药', '用法': '口服', '副作用': '胃肠道反应' } },
    { id: 'drug_2', name: '二甲双胍', type: 'drug', description: '双胍类降糖药，糖尿病一线治疗药物', properties: { '类型': '降糖药', '用法': '口服', '副作用': '胃肠道反应' } },
    
    // 科室节点
    { id: 'dept_1', name: '心血管内科', type: 'department', description: '诊治心血管系统疾病的专科', properties: { '主要疾病': '高血压、冠心病', '医生数': '12人' } },
    { id: 'dept_2', name: '内分泌科', type: 'department', description: '诊治内分泌系统疾病的专科', properties: { '主要疾病': '糖尿病、甲状腺疾病', '医生数': '8人' } }
  ],
  links: [
    { source: 'disease_1', target: 'symptom_1', type: '可能引起', strength: 0.8 },
    { source: 'disease_3', target: 'symptom_2', type: '典型症状', strength: 0.9 },
    { source: 'disease_2', target: 'symptom_3', type: '典型症状', strength: 0.9 },
    { source: 'disease_1', target: 'drug_1', type: '治疗药物', strength: 0.7 },
    { source: 'disease_2', target: 'drug_2', type: '首选药物', strength: 0.9 },
    { source: 'disease_1', target: 'dept_1', type: '就诊科室', strength: 1.0 },
    { source: 'disease_3', target: 'dept_1', type: '就诊科室', strength: 1.0 },
    { source: 'disease_2', target: 'dept_2', type: '就诊科室', strength: 1.0 }
  ]
}

// 方法定义
const handleSearch = (query) => {
  if (!query) {
    resetGraph()
    return
  }
  
  // 搜索逻辑
  const matchedNodes = mockGraphData.nodes.filter(node => 
    node.name.includes(query) || node.description.includes(query)
  )
  
  if (matchedNodes.length > 0) {
    highlightNodes(matchedNodes)
  } else {
    ElMessage.info('未找到相关知识节点')
  }
}

const setFilter = (filter) => {
  activeFilter.value = filter
  filterGraph(filter)
}

const filterGraph = (filter) => {
  loading.value = true
  
  setTimeout(() => {
    if (filter === 'all') {
      renderGraph(mockGraphData)
    } else {
      const filteredData = {
        nodes: mockGraphData.nodes.filter(node => node.type === filter),
        links: mockGraphData.links.filter(link => {
          const sourceNode = mockGraphData.nodes.find(n => n.id === link.source)
          const targetNode = mockGraphData.nodes.find(n => n.id === link.target)
          return sourceNode?.type === filter || targetNode?.type === filter
        })
      }
      renderGraph(filteredData)
    }
    loading.value = false
  }, 500)
}

const resetGraph = () => {
  renderGraph(mockGraphData)
}

const highlightNodes = (nodes) => {
  // 高亮显示匹配的节点
  console.log('Highlighting nodes:', nodes)
}

const focusNode = (nodeId) => {
  const node = mockGraphData.nodes.find(n => n.id === nodeId)
  if (node) {
    selectedNode.value = {
      ...node,
      relations: mockGraphData.links
        .filter(link => link.source === nodeId || link.target === nodeId)
        .map(link => ({
          id: link.source === nodeId ? link.target : link.source,
          type: link.type,
          targetName: mockGraphData.nodes.find(n => n.id === (link.source === nodeId ? link.target : link.source))?.name
        }))
    }
  }
}

const exploreCategory = (category) => {
  setFilter(category.name === '常见疾病' ? 'disease' : 
             category.name === '症状体征' ? 'symptom' :
             category.name === '药物治疗' ? 'drug' : 'department')
}

const getNodeTypeColor = (type) => {
  const colors = {
    disease: 'danger',
    symptom: 'warning', 
    drug: 'success',
    department: 'info'
  }
  return colors[type] || 'default'
}

const getNodeTypeName = (type) => {
  const names = {
    disease: '疾病',
    symptom: '症状',
    drug: '药物', 
    department: '科室'
  }
  return names[type] || '未知'
}

const renderGraph = (data) => {
  // 这里应该使用D3.js或ECharts等库来渲染知识图谱
  // 为了演示，我们只是更新统计数据
  totalNodes.value = data.nodes.length
  totalRelations.value = data.links.length
  
  // 模拟图谱渲染
  if (graphCanvas.value) {
    graphCanvas.value.innerHTML = `
      <div style="
        display: flex; 
        justify-content: center; 
        align-items: center; 
        height: 100%; 
        font-size: 18px; 
        color: #666;
        flex-direction: column;
        gap: 20px;
      ">
        <div style="font-size: 48px;">🧠</div>
        <div>医疗知识图谱可视化</div>
        <div style="font-size: 14px; opacity: 0.7;">
          显示 ${data.nodes.length} 个节点，${data.links.length} 个关联关系
        </div>
        <div style="font-size: 12px; opacity: 0.5;">
          点击下方分类探索不同类型的医疗知识
        </div>
      </div>
    `
  }
}

// 组件挂载
onMounted(() => {
  nextTick(() => {
    setTimeout(() => {
      renderGraph(mockGraphData)
      loading.value = false
    }, 1000)
  })
})
</script>

<style scoped>
.knowledge-graph {
  min-height: 100vh;
  background: #f5f7fa;
}

.container {
  max-width: 1400px;
  margin: 0 auto;
  padding: 0 24px;
}

/* 页面头部 */
.graph-header {
  background: white;
  padding: 32px 0;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.page-title {
  font-size: 1.75rem;
  font-weight: 700;
  color: #262626;
  margin-bottom: 8px;
  display: flex;
  align-items: center;
  gap: 12px;
}

.title-icon {
  font-size: 2rem;
  color: #722ed1;
}

.page-subtitle {
  color: #8c8c8c;
  font-size: 1rem;
  margin: 0;
}

.graph-stats {
  display: flex;
  gap: 32px;
}

.stat-item {
  text-align: center;
}

.stat-number {
  display: block;
  font-size: 2rem;
  font-weight: 700;
  color: #722ed1;
}

.stat-label {
  font-size: 14px;
  color: #8c8c8c;
}

/* 控制面板 */
.control-panel {
  background: white;
  padding: 24px 0;
  border-bottom: 1px solid #f0f0f0;
}

.panel-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  gap: 24px;
}

.search-section {
  flex: 1;
  max-width: 400px;
}

.search-input :deep(.el-input__inner) {
  border-radius: 8px;
}

.filter-section {
  display: flex;
  gap: 12px;
}

/* 图谱容器 */
.graph-container {
  padding: 32px 0;
}

.graph-wrapper {
  display: flex;
  gap: 24px;
  height: 600px;
}

.graph-canvas {
  flex: 1;
  background: white;
  border-radius: 12px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
  position: relative;
}

.detail-panel {
  width: 320px;
  background: white;
  border-radius: 12px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
  padding: 24px;
  overflow-y: auto;
}

.panel-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 24px;
}

.node-title {
  font-size: 18px;
  font-weight: 600;
  color: #262626;
  margin: 0;
}

.panel-content h4 {
  font-size: 14px;
  font-weight: 600;
  color: #262626;
  margin: 16px 0 8px 0;
}

.node-description p {
  color: #595959;
  line-height: 1.6;
  margin: 0;
}

.relation-list {
  list-style: none;
  padding: 0;
  margin: 0;
}

.relation-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 12px;
  margin-bottom: 4px;
  background: #fafafa;
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.relation-item:hover {
  background: #e6f7ff;
  border-color: #1890ff;
}

.relation-type {
  font-size: 12px;
  color: #1890ff;
  font-weight: 500;
}

.relation-target {
  font-size: 13px;
  color: #262626;
}

.property-grid {
  display: grid;
  gap: 8px;
}

.property-item {
  display: flex;
  justify-content: space-between;
  padding: 6px 12px;
  background: #fafafa;
  border-radius: 4px;
}

.property-key {
  font-size: 12px;
  color: #8c8c8c;
}

.property-value {
  font-size: 12px;
  color: #262626;
  font-weight: 500;
}

/* 知识分类 */
.knowledge-categories {
  padding: 48px 0;
  background: white;
}

.section-title {
  text-align: center;
  font-size: 1.5rem;
  font-weight: 600;
  color: #262626;
  margin-bottom: 32px;
}

.categories-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
  gap: 24px;
}

.category-card {
  display: flex;
  align-items: center;
  gap: 16px;
  padding: 24px;
  background: #fafafa;
  border-radius: 12px;
  cursor: pointer;
  transition: all 0.3s ease;
  border: 1px solid transparent;
}

.category-card:hover {
  background: white;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
  border-color: #1890ff;
  transform: translateY(-2px);
}

.category-icon {
  width: 56px;
  height: 56px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-size: 24px;
  flex-shrink: 0;
}

.category-name {
  font-size: 16px;
  font-weight: 600;
  color: #262626;
  margin: 0 0 4px 0;
}

.category-description {
  color: #8c8c8c;
  font-size: 14px;
  margin: 0 0 8px 0;
  line-height: 1.4;
}

.category-stats {
  font-size: 12px;
  color: #1890ff;
  font-weight: 500;
}

/* 响应式设计 */
@media (max-width: 1024px) {
  .graph-wrapper {
    flex-direction: column;
    height: auto;
  }
  
  .graph-canvas {
    height: 400px;
  }
  
  .detail-panel {
    width: 100%;
  }
  
  .panel-content {
    flex-direction: column;
    align-items: stretch;
  }
}

@media (max-width: 768px) {
  .header-content {
    flex-direction: column;
    align-items: flex-start;
    gap: 16px;
  }
  
  .graph-stats {
    width: 100%;
    justify-content: space-around;
  }
  
  .categories-grid {
    grid-template-columns: 1fr;
  }
}
</style> 